/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* rotateRight(ListNode* head, int k) {
        if(head == nullptr || head->next == nullptr || k == 0)
            return head;

        // 计算结点个数
        int n = 0;
        ListNode *cur = head;
        while(cur)
        {
            n++;
            cur = cur->next;
        }

        // 真正旋转次数
        k %= n;
        if(k == 0)
            return head;

        cur = head;
        ListNode *prev = nullptr;
        int count = n - k;
        while(count--)
        {
            prev = cur;
            cur = cur->next;
        }

        prev->next = nullptr;
        ListNode *newHead = cur;
        while(cur->next)
            cur = cur->next;

        cur->next = head;
        return newHead;
    }
};